package com.moter.demo01.juc.alllocks.spinlock;

import java.util.concurrent.atomic.AtomicReference;

/**
 * 自旋锁和适应性自旋锁
 */
public class SpinLock {
    private final AtomicReference<Thread> lock = new AtomicReference<>();

//    private static volatile boolean is_success=true;//判断之前的锁，拿到没有资源没有
    private static volatile int times=5000;//初始自旋次数
    public void lock(){
        Thread thread = Thread.currentThread();
        while (!lock.compareAndSet(null,thread)){
        }
    }
    public void unLock(){
        Thread thread = Thread.currentThread();
        lock.compareAndSet(thread,null);
    }

    public void adaptiveLock(){
        Thread thread = Thread.currentThread();
        int time = times;
        while (!lock.compareAndSet(null,thread)){
            time--;
            if(time==0){
                times=2000;//上一次失败的自旋次数
                thread.interrupt();
                throw new RuntimeException( thread.getName()+"\t没有拿到资源，终止");
            }
        }
        times=5000;//上一次成功的自旋次数
    }
}
